const fs = require('fs')
const path = require('path')

const BUNDLE_FILE = path.resolve(__dirname, '../src/app.bundle.js')
const BUNDLE_FILE_WRITE_STREAM = fs.createWriteStream(BUNDLE_FILE, { flags: 'w' })

function append({ content, filename }) {
  if (filename) {
    const filepath = `src/${filename}`
    console.log(`appending ${filepath}`)
    BUNDLE_FILE_WRITE_STREAM.write(`/************************ ${filename} ************************/\n`)
    BUNDLE_FILE_WRITE_STREAM.write(
      fs.readFileSync(
        path.resolve(__dirname, `../${filepath}`)
      ).toString()
    )
    BUNDLE_FILE_WRITE_STREAM.write(`/******************** EOF ${filename} ************************/\n`)
  } else {
    BUNDLE_FILE_WRITE_STREAM.write(`/************************ - ************************/\n`)
    BUNDLE_FILE_WRITE_STREAM.write(
      content
    )
    BUNDLE_FILE_WRITE_STREAM.write(`/******************** EOF - ************************/\n`)
  }
}

console.log(`clearing ${BUNDLE_FILE}`)

BUNDLE_FILE_WRITE_STREAM.write('/** This script is generated by scripts/build-app.js */\n\n')

append({ filename: 'entry.js' })
append({ filename: 'dict.js' })
append({ filename: 'scheme-list.js' })
append({ filename: 'mode-list.js' })
append({ filename: 'core.js' })
append({ filename: 'setting.js' })
append({ filename: 'action.js' })
append({ content: 'Shuang.app.action.init()\n' })

BUNDLE_FILE_WRITE_STREAM.end()

console.log(`bundled: ${BUNDLE_FILE}`)